from django.contrib.auth.mixins import LoginRequiredMixin

from Account.models import Account
from sportsground.utils.Res import Res


class LoginRequiredUser(LoginRequiredMixin):
    """ 自定义用户登陆返回JSON """

    def dispatch(self, request, *args, **kwargs):
        # 用户角色判断
        if not request.user.is_authenticated or request.user.role != Account.Roles.User:
            return self.handle_no_permission()
        return super().dispatch(request, *args, **kwargs)

    def handle_no_permission(self):
        return Res.Json(Res.UserUnvalid)


class LoginRequiredVenue(LoginRequiredMixin):
    """ 自定义馆场方登陆返回JSON """

    def dispatch(self, request, *args, **kwargs):
        # 馆场方角色判断
        if not request.user.is_authenticated or request.user.role != Account.Roles.Venue:
            return self.handle_no_permission()
        return super().dispatch(request, *args, **kwargs)

    def handle_no_permission(self):
        return Res.Json(Res.UserUnvalid)


class LoginRequired:
    """ 登陆验证装饰器 """

    def User(func):
        # 检测是否为用户
        def inner(view, request, *args, **kwargs):
            if not request.user.is_authenticated or request.user.role != Account.Roles.User:
                return Res.Json(Res.UserUnvalid)
            return func(view, request, *args, **kwargs)

        return inner

    def Venue(func):
        # 检测是否为馆场方
        def inner(view, request, *args, **kwargs):
            if not request.user.is_authenticated or request.user.role != Account.Roles.Venue:
                return Res.Json(Res.UserUnvalid)
            return func(view, request, *args, **kwargs)

        return inner
